//
//  QRCodeLoginViewController.m
//  MPWeChatDemo
//
//  Created by HappyMilk 01 on 2017/5/1.
//  Copyright © 2017年 srulos. All rights reserved.
//

#import "QRCodeLoginViewController.h"
#import "LoginHeader.h"

#define LOC_STR(str)  NSLocalizedStringFromTable(str, @"Login", nil)

@interface QRCodeLoginViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *qrCode_imageView;
@property (weak, nonatomic) IBOutlet UILabel *login_label;
@property (weak, nonatomic) IBOutlet UIImageView *user_icon;
@property (weak, nonatomic) IBOutlet UILabel *user_name;

@property(nonatomic,strong) UIActivityIndicatorView *activity;

@property(nonatomic,assign) BOOL shouldRefreshQRCode;


@end

@implementation QRCodeLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ADD_OBSERVER(self, @selector(onUpdateQRCodeStatus:), NOTIFICATION_UPDATE_QRCODE_STATUS, nil)
    
    [self requestQRCode];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onQRCodeImageTouched)];
    [_qrCode_imageView addGestureRecognizer:gesture];
}


-(void)onQRCodeImageTouched{
    [self requestQRCode];
}

-(void)requestQRCode{
    _user_name.hidden = true;
    _user_icon.hidden = true;
    _qrCode_imageView.userInteractionEnabled = false;
    [_qrCode_imageView setImage:nil];
    [self showIndicator];
    self.login_label.text = @"正在加载二维码...";
    [MPWeChat asyncGetFreeQRCode:^(UIImage *image) {
        if (image != nil) {
            [self.qrCode_imageView setImage:image];
            self.login_label.text = @"请使用手机，打开微信扫一扫登录";
            [self.activity stopAnimating];
        }else{
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.login_label.text = @"二维码加载失败，点击重新获取";
                [self.qrCode_imageView setImage:[UIImage imageNamed:@"qr_code_refresh.jpg"]];
                _qrCode_imageView.userInteractionEnabled = true;
                [self.activity stopAnimating];
            });
        }
    }];
}


-(void)onUpdateQRCodeStatus:(id)sender
{
    if ([MPWeChat stander].m_currentQRCodeStatus == QS_LOGIN_SUCCESS) {
        _login_label.text = @"登录成功！";
        [_qrCode_imageView setImage:[UIImage imageNamed:@"qr_code_success.jpg"]];
        _qrCode_imageView.userInteractionEnabled = false;
        
        [self dismissViewControllerAnimated:true completion:nil];
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"" message:LOC_STR(@"login successful") delegate:nil cancelButtonTitle:LOC_STR(@"Confirm") otherButtonTitles:nil, nil];
        [alertview show];
        
    }
    else if([MPWeChat stander].m_currentQRCodeStatus == QS_SCAN_EXPIRED){
        [_qrCode_imageView setImage:[UIImage imageNamed:@"qr_code_refresh.jpg"]];
        _qrCode_imageView.userInteractionEnabled = true;
        _qrCode_imageView.hidden = false;
        _user_icon.hidden = true;
        _user_name.hidden = true;
        self.login_label.text = @"二维码过期，点击重新获取";
    }
    else if([MPWeChat stander].m_currentQRCodeStatus == QS_SCAN_SUCCESS){
        _qrCode_imageView.hidden = true;
        _user_name.hidden = false;
        _user_icon.hidden = false;
        _user_name.text = [MPWeChat stander].m_currentQRCodeUserInfoNickName;
        _login_label.text = @"扫码成功，请在手机上轻触确认登录";
    
        //用户头像
        NSString *iconUrl = [MPWeChat stander].m_currentQRCodeUserInfoHeadImgUrl;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSData *resultData = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconUrl]];
            UIImage *img = [UIImage imageWithData:resultData];
            dispatch_sync(dispatch_get_main_queue(), ^{
                _user_icon.image = img;
            });
        });
    }
    else if([MPWeChat stander].m_currentQRCodeStatus == QS_LOGIN_CANCEL){//用户扫完有点了取消登陆
        //直接从新获取二维码
        _qrCode_imageView.hidden = false;
        _user_name.hidden = true;
        _user_icon.hidden = true;

        [self requestQRCode];
    }
    else{
        _qrCode_imageView.userInteractionEnabled = true;
        self.login_label.text = @"扫码失败！点击重新获取";
        [_qrCode_imageView setImage:[UIImage imageNamed:@"qr_code_refresh.jpg"]];
    }
}

//小菊花
-(void)showIndicator{
    self.activity= [[UIActivityIndicatorView alloc]initWithFrame:self.qrCode_imageView.frame];
    
    self.activity.center = CGPointMake([UIScreen mainScreen].bounds.size.width*0.5, self.activity.center.y);
    
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    
    self.activity.color= [UIColor blackColor];
    
    self.activity.hidesWhenStopped=YES;
    
    [self.view addSubview:self.activity];
    [self.activity startAnimating];
}

- (IBAction)onClose:(id)sender {
    [self dismissViewControllerAnimated:true completion:nil];
    [MPWeChat asyncFreeQRCode];
}

@end
